<template>
    <div class="card" style="display: flex;">
        <div>
            <el-input style="width: 240px;" v-model="data.searchname" placeholder="请输入员工姓名或员工编号查询"
                prefix-icon="Search"></el-input>
            <el-button style="margin-left: 10px;" type="primary" @click="load()">查询</el-button>
            <el-button style="margin-left: 10px;" @click="reset()">重置</el-button>
        </div>
        <div style="margin-left: auto;">
            <el-button style="margin-left: 10px;" color="green" @click="add()">新增员工</el-button>
            <el-button style="margin-left: 10px;" type="primary" @click="retire()">一键退休</el-button>
            <el-button style="margin-left: 10px;" type="danger" @click="delBatch()">批量删除</el-button>
        </div>
    </div>

    <div class="card">
        <el-table :data="data.employeelist" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="员工姓名" prop="employeeName" />
            <el-table-column label="员工年龄" prop="employeeAge" />
            <el-table-column label="职位" prop="position" :filters="[
                { text: '普通员工', value: '普通员工' },
                { text: '小组长', value: '小组长' },
                { text: '主管', value: '主管' },
                { text: '部长', value: '部长' },
                { text: '经理', value: '经理' },
                { text: '总经理', value: '总经理' },
            ]" :filter-method="filterHandler" />
            <el-table-column label="工资" prop="employeeSalary" />
            <el-table-column label="个人养老金账户" prop="employeePension" />
            <el-table-column label="操作">
                <template #default="scoped">
                    <el-button type="primary" :icon="Edit" @click="employeeInfo(scoped.row)" circle></el-button>
                    <el-button type="danger" :icon="Delete" @click="deleteEmployee(scoped.row)" circle></el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 15px;">
            <el-pagination v-model:current-page="data.pageNumber" v-model:page-size="data.pageSize"
                :page-sizes="[1, 5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="data.total"
                @size-change="load()" @current-change="load()" />
        </div>
    </div>

    <el-dialog title="员工信息" v-model="data.formVisable" width="500" :destory-on-close=true>
        <el-form ref="formRef" :rules="data.rules" :model="data.form">
            <el-form-item label="员工编号 ">
                <el-input v-model="data.form.employeeId" disabled></el-input>
            </el-form-item>
            <el-form-item label="员工姓名 " prop="employeeName">
                <el-input v-model="data.form.employeeName"></el-input>
            </el-form-item>
            <el-form-item label="员工电话 " prop="employeePhone">
                <el-input v-model="data.form.employeePhone"></el-input>
            </el-form-item>
            <el-form-item label="员工性别 " prop="employeeSex">
                <el-radio-group v-model="data.form.employeeSex">
                    <el-radio value="男">男</el-radio>
                    <el-radio value="女">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="员工出生日期 " prop="employeeAge">
                <el-date-picker v-model="data.form.employeeAge" placeholder="选择出生日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="员工工资 " prop="employeeSalary">
                <el-input v-model="data.form.employeeSalary"></el-input>
            </el-form-item>
            <el-form-item label="员工职位 " prop="position">
                <el-select v-model="data.form.position">
                    <el-option label="普通员工" value="普通员工"></el-option>
                    <el-option label="小组长" value="小组长"></el-option>
                    <el-option label="主管" value="主管"></el-option>
                    <el-option label="部长" value="部长"></el-option>
                    <el-option label="经理" value="经理"></el-option>
                    <el-option label="总经理" value="总经理"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="个人养老金账户" prop="employeePension">
                <el-input v-model="data.form.employeePension"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleCancle()">取消</el-button>
                <el-button type="primary" @click="handleConfirm()">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import request from '@/utils/request';
import { Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { nextTick, reactive, ref } from 'vue';


const data = reactive({
    pageNumber: 1,
    pageSize: 5,
    total: 0,
    formVisable: false,
    employeelist: [],
    searchname: '',
    form: {
        employeeId: '',
        enterpriseId: JSON.parse(localStorage.getItem('enterprise')).enterpriseId,
        employeeName: '',
        employeePhone: '',
        employeeSex: '',
        employeeAge: '',
        employeeSalary: '',
        position: '',
        isleave: '',
        employeePension: '',
    },
    employees: [],
    rules: {
        employeeName: [
            { required: true, message: '请输入员工姓名', trigger: ['change', 'blur'] },
            { min: 2, max: 10, message: '长度在 2 到 5 个字符', trigger: ['change', 'blur'] }
        ],
        employeePhone: [
            { required: true, message: '请输入员工电话', trigger: ['change', 'blur'] },
            { pattern: /^[1-9]\d{10}$/, message: '请输入有效的手机号码', trigger: ['change', 'blur'] }
        ],
        employeeSex: [
            { required: true, message: '请输入员工性别', trigger: ['change', 'blur'] },
        ],
        employeeAge: [
            { required: true, message: '请输入员工年龄', trigger: ['change', 'blur'] },
            {
                validator: (rule, value, callback) => {
                    if (!value) {
                        callback(new Error('请选择员工出生日期'));
                    } else {
                        let birthDate = new Date(value); // 将日期字符串转换为 Date 对象
                        let today = new Date(); // 当前日期
                        let age = today.getFullYear() - birthDate.getFullYear(); // 计算年龄
                        let monthDiff = today.getMonth() - birthDate.getMonth();
                        let dayDiff = today.getDate() - birthDate.getDate();

                        // 如果当前月份和日期小于出生月份和日期，年龄减 1
                        if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
                            age--;
                        }
                        if (age < 20 || age > 63) {
                            callback(new Error('年龄必须在 20 到 63岁之间'));
                        } else {
                            callback(); // 校验通过
                        }
                    }
                },
                trigger: ['change', 'blur']
            }
        ],
        employeeSalary: [
            { required: true, message: '请输入员工工资', trigger: ['change', 'blur'] },
            { pattern: /^[1-9][0-9]{1,6}(\.[0-9]{0,2})?$/, message: '请输入有效的金额，最多两位小数', trigger: ['change',] },
            {
                validator: (rule, value, callback) => {
                    if (value < 3500) {
                        callback(new Error('工资不能低于 3500'));
                    } else {
                        callback(); // 校验通过
                    }
                },
                trigger: ['change', 'blur']
            }
        ],
        employeePension: [
            { required: true, message: '请输入员工养老金账户', trigger: ['change', 'blur'] },
            { pattern: /^[1-9][0-9]{1,8}(\.[0-9]{0,2})?$/, message: '请输入有效的金额，最多两位小数', trigger: ['change',] },
            {
                validator: (rule, value, callback) => {
                    if (value < 0) {
                        callback(new Error('养老金账户不能为负数'));
                    } else {
                        callback(); // 校验通过
                    }
                },
                trigger: ['change', 'blur']
            }
        ],
        position: [
            { required: true, message: '请输入员工职位', trigger: ['change', 'blur'] }
        ],
    }

})
const formRef = ref()
const load = () => {//加载所有员工
    request.get('/employee/searchPage', {
        params: {
            pageNumber: data.pageNumber,
            pageSize: data.pageSize,
            employeeName: data.searchname,
            enterpriseId: JSON.parse(localStorage.getItem('enterprise')).enterpriseId,
            isleave: 0,//在职员工    
        }
    }).then(res => {
        data.employeelist = res.data.list
        data.total = res.data.total
    })
}
load()


const filterHandler = (value,row,column) => {
  const property = column['property']
  return row[property] === value
}
const resetform = () => {//重置表单
    data.form = {
        employeeId: '',
        enterpriseId: JSON.parse(localStorage.getItem('enterprise')).enterpriseId,
        employeeName: '',
        employeePhone: '',
        employeeSex: '',
        employeeAge: '',
        employeeSalary: '',
        position: '',
        isleave: 0,
        employeePension: '',
    }
}
const employeeInfo = (row) => {//打开员工个人详细信息
    data.formVisable = true
    data.form = { ...row }
}
const add = () => {//打开新增管员工信息界面
    data.formVisable = true
    nextTick(() => {
        formRef.value.clearValidate(); // 清除表单验证状态
        resetform()// 清空表单数据
        formRef.value.resetFields(); // 重置表单
    })
}
const deleteEmployee = (row) => {//删除员工
    ElMessageBox.confirm('删除数据后无法恢复，确认删除？', { type: 'warning' }).then(() => {
        request.post('employee/delete', row).then(res => {
            if (res.code = '200') {
                ElMessage.success("删除成功")
                load()
            }
            else {
                ElMessage.error(res.message)
            }
        })
    }).catch()
}
const reset = () => {
    data.employee.employeeName = ''
    searchname = ''
    load()
}

const handleCancle = () => {
    data.formVisable = false
    resetform()
}
const handleConfirm = () => {//修改或新增员工信息
    formRef.value.validate((valid) => {
        if (!valid) {
            ElMessage.error('请填写完整信息')
            return false
        }
    })
    //根据员工编号判断是修改还是新增
    if (data.form.employeeId !== '' && data.form.employeeId !== undefined && data.form.employeeId !== null) {
        request.post('/employee/update', data.form).then(res => {
            if (res.code === '200') {
                ElMessage.success('修改成功')
                load()
            }
            else {
                ElMessage.error(res.message)
            }
        })
    }
    else {
        request.post('/employee/add', data.form).then(res => {
            if (res.code === '200') {
                ElMessage.success('添加成功')
                load()
            }
            else {
                ElMessage.error(res.message)
            }
        })
    }
    data.formVisable = false
}
const handleSelectionChange = (rows) => {//选中的行对象
    data.employees = rows
}

const retire=()=>{//批量退休
    ElMessageBox.confirm('此操作会将符合退休年龄的员工退休', { type: 'warning' }).then(() => {
        request.post("/employee/retire", { enterpriseId: data.form.enterpriseId }).then(res => {
            if (res.code = '200') {
                ElMessage.success("本次退休成功" + res.data + "人")
                load()
            }
            else {
                ElMessage.error(res.message)
            }
        })
    })
}


const delBatch = () => {
    if (data.employees.length === 0) {
        ElMessage.warning("请选择数据")
        return
    }
    ElMessageBox.confirm('删除数据后无法恢复，确认删除？', { type: 'warning' }).then(() => {
        request.post("/employee/deletebatch", data.employees).then(res => {
            if (res.code = '200') {
                ElMessage.success("删除成功")
                load()
            }
            else {
                ElMessage.error(res.message)
            }
        })
    })
}
</script>

<style scoped></style>